package com.zywl.web.controller.sys;

import com.github.pagehelper.util.StringUtil;
import com.zywl.core.beans.Company;
import com.zywl.core.beans.Demand;
import com.zywl.core.beans.Dictionary;
import com.zywl.core.beans.User;
import com.zywl.service.CompanyService;
import com.zywl.service.DemandService;
import com.zywl.service.DictionaryService;
import com.zywl.service.MemberService;
import com.zywl.utils.models.AjaxResult;
import com.zywl.utils.models.PageData;
import com.zywl.utils.models.PageResult;
import com.zywl.utils.utils.Constants;
import com.zywl.utils.utils.MapUtil;
import com.zywl.utils.utils.enums.LogTypeEnum;
import com.zywl.web.controller.base.BaseController;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/demand")
public class DemandController extends BaseController {
    @Autowired
    private DemandService demandService;
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private MemberService memberService;

    @GetMapping("/demandListPage")
    public ModelAndView demandListPage() {
        ModelAndView mav = new ModelAndView("demand/demandListPage");
        return mav;
    }


    @PostMapping("/getdemandList")
    public PageResult getdemandList(HttpServletRequest request, PageData pageData) {

        Map<String, Object> condition = MapUtil.changeMap(request.getParameterMap());
        PageResult pageResult = null;
        try {
            pageResult = putToResult(demandService.getPageInfo(condition, pageData));
            List<Demand> list = pageResult.getData();
            List<Dictionary> dictionaryList = dictionaryService.getDictionaryByType("indu");
            List<Dictionary> tagsList = dictionaryService.getDictionaryByType("tags");
            Map<String,String> map = new HashMap<>();
            for (Dictionary dictionary : dictionaryList){
                map.put(dictionary.getDisCode(),dictionary.getDisCodeName());
            }
            Map<String,String> tagmap = new HashMap<>();
            for (Dictionary dictionary : tagsList){
                tagmap.put(dictionary.getDisCode(),dictionary.getDisCodeName());
            }
            for (Demand demand : list){
                String[] indus = demand.getDedIndustrys().split(",");
                String induName = "";
                for (String str : indus){
                    if(StringUtil.isNotEmpty(str)){
                        induName += map.get(str) + ",";
                    }
                }
                demand.setDedIndustrys(induName.substring(0,induName.length()-1));

                String[] tags = demand.getDedTags().split(",");
                String tagsName = "";
                for (String str : tags){
                    if(StringUtil.isNotEmpty(str)){
                        tagsName += tagmap.get(str) + ",";
                    }
                }
                demand.setDedTags(tagsName.substring(0,tagsName.length()-1));
            }
            pageResult.setData(list);
        } catch (Exception e) {
            logger.error("获取公司列表异常", e);
        }
        return pageResult;
    }

    @GetMapping("/demandSubmitPage")
    public ModelAndView demandSubmitPage(String id, HttpSession session) {
        ModelAndView mav = new ModelAndView("demand/demandSubmitPage");
        try {
            if (StringUtils.isNotEmpty(id)) {
                Demand demand = demandService.getById(Long.parseLong(id));
                List<Dictionary> dictionaryList = dictionaryService.getDictionaryByType("indu");
                List<Dictionary> tagsList = dictionaryService.getDictionaryByType("tags");
                Map<String,String> map = new HashMap<>();
                for (Dictionary dictionary : dictionaryList){
                    map.put(dictionary.getDisCode(),dictionary.getDisCodeName());
                }
                Map<String,String> tagmap = new HashMap<>();
                for (Dictionary dictionary : tagsList){
                    tagmap.put(dictionary.getDisCode(),dictionary.getDisCodeName());
                }

                String[] indus = demand.getDedIndustrys().split(",");
                String induName = "";
                for (String str : indus){
                    if(StringUtil.isNotEmpty(str)){
                        induName += map.get(str) + ",";
                    }
                }
                demand.setDedIndustrys(induName.substring(0,induName.length()-1));

                String[] tags = demand.getDedTags().split(",");
                String tagsName = "";
                for (String str : tags){
                    if(StringUtil.isNotEmpty(str)){
                        tagsName += tagmap.get(str) + ",";
                    }
                }
                demand.setDedTags(tagsName.substring(0,tagsName.length()-1));
                mav.addObject("demand", demand);
            }
        } catch (Exception e) {
            logger.error("获取数据异常", e);
        }
        return mav;
    }

    @PostMapping("/demandSubmit")
    public AjaxResult demandSubmit(HttpServletRequest request, Demand form) {
        AjaxResult ar = new AjaxResult();
        if (form != null) {
            Demand demand = null;
            String old = null;
            Date date = new Date();
            try {
                if (form.getDedId() != null) {
                    demand = demandService.getById(form.getDedId());
                    old = demand.getDedName();
                    form.setDedStt(demand.getDedStt());
                    form.setDedCreateTime(demand.getDedCreateTime());
                } else {
                    demand = new Demand();
                    form.setDedStt("0");
                    form.setDedCreateTime(date);

                    User user = (User) request.getSession().getAttribute(Constants.USER_SESSION_KEY);
                    if (user.getUsrAssociationId() != null){
                        form.setDedAssociationid(user.getUsrAssociationId());
                    }else{
                        ar.error("平台管理员无法帮忙创建需求");
                        return ar;
                    }

                    //查询公司名称是否已存在
                    Map<String, Object> condition = new HashMap<>();
                    condition.put("DedName",form.getDedName());
                    condition.put("DedStt","0");
                    int count = demandService.getCountByParams(condition);
                    if(count > 0){
                        ar.error("该需求名称已存在，请修改");
                        return ar;
                    }
                }

                form.setDedModifyTime(date);
                BeanUtils.copyProperties(form, demand);

                if (form.getDedId() == null) {
                    demandService.save(demand);
                } else {
                    demandService.update(demand);
                }
            } catch (Exception e) {
                logger.error("提交需求信息异常", e);
                ar.error("提交需求信息异常", e);
                return ar;
            }

            if (form.getDedId() == null) {
                saveLog(request, LogTypeEnum.DEMAND.getKey(), "需求新增-" + form.getDedName());
                ar.success("新增成功");
            } else if (old != null && !old.equals(form.getDedName())) {
                saveLog(request, LogTypeEnum.DEMAND.getKey(), "需求修改-" + old + "→" + form.getDedName());
                ar.success("修改成功");
            } else {
                saveLog(request, LogTypeEnum.DEMAND.getKey(), "需求修改-" + form.getDedName());
                ar.success("修改成功");
            }
        } else {
            ar.error("提交失败，参数为空");
        }
        return ar;
    }

    @PostMapping("/demandDelete")
    public AjaxResult demandDelete(HttpServletRequest request, Long id) {
        AjaxResult ar = new AjaxResult();
        try {
            Demand demand = demandService.getById(id);
            String demandNickName = demand.getDedName();
            demand.setDedStt("1");
            demandService.update(demand);//逻辑删除用户
            saveLog(request, LogTypeEnum.DEMAND.getKey(), "需求删除-" + demandNickName);
            ar.success("删除成功");
        } catch (Exception e) {
            ar.error("删除需求异常", e);
            logger.error("删除需求异常", e);
        }
        return ar;
    }
}
